/**
 * Created by lenovo on 2017/7/20.
 */
let config = require('../../config');
let OAuth = require('wechat-oauth');
let client = new OAuth(config.app.appid, config.app.appsecret);
let DBPool = require('../dao/DBConnectPool');
let async = require('async');
let sign = require('../../common/utils/sign.js');
let Jsapi = require('./JsapiTicketController');
let request = require('request');

module.exports = {
    getMemberInformation: function (req, res, callback) {
      if (req.signedCookies.userinfo && req.signedCookies.userinfo.openid){
          console.log('WX-Member-log: line(13)'+ req.signedCookies.userinfo);
          callback(null,null,req.signedCookies.userinfo);
      } else {
          let code = req.query.code;
          if (!code){
              callback('用户信息丢失，请从公众号菜单重新进入！',107);
          } else {
              try {
                  client.getAccessToken(req.query.code, function (err, result) {
                      if (err){
                          console.log('WX-Member-log: line(27)'+ err);
                          callback('微信服务器链接失败，请稍后重试！',105)
                      } else {
                          let url = 'https://api.weixin.qq.com/sns/userinfo?access_token='+ result.data.access_token +'&openid='+ result.data.openid;
                          request.get(url,function (err, response, body) {
                              let responseJson = JSON.parse(body);
                              if (responseJson.errcode){
                                  console.log('WX-Member-log: line(34)'+ responseJson.errmsg);
                                  callback(responseJson.errmsg,105)
                              } else {
                                  console.log('WX-Member-log: line(40)'+ responseJson);
                                  res.cookie('userinfo', responseJson, {
                                      maxAge: 1000 * 60 * 60 * 24,
                                      signed: true
                                  });
                                  callback(null,null,responseJson);
                              }
                          });
                          //console.log('WX-Member-log: line(23)'+ result.data.openid);
                          // client.getUser(result.data.openid, function (err, result) {
                          //     if (err){
                          //         console.log('WX-Member-log: line(26)'+ err);
                          //         callback(err,105)
                          //     } else {
                          //         console.log('WX-Member-log: line(29)'+ result);
                          //         res.cookie('userinfo', result, {
                          //             maxAge: 1000 * 60 * 60 * 24,
                          //             signed: true
                          //         });
                          //         callback(null,null,result);
                          //     }
                          // })
                      }
                  });
              }catch (error) {
                  callback(error,105);
              }
          }
      }
    },
    setMemberInformation:function (req, res, callback) {
        if (req.signedCookies.userinfo && req.signedCookies.userinfo.openid){
            let date = new Date();
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            let D = date.getDate() < 10 ? '0'+ date.getDate():date.getDate();
            const mid = ' ';
            let h = date.getHours() + ':';
            let m = date.getMinutes() + ':';
            let s = date.getSeconds();
            let timestamp = Y + M + D + mid + h + m + s;

            let userInfo = req.signedCookies.userinfo;
            let phoneNumber = req.body.phonenumber;
            console.log('WX-Member-log: line(65)'+ req.signedCookies.userinfo);
            DBPool.getPoolConnection('mtsc',function (err, connection) {
                if (err) {
                    callback('保存用户信息失败！',106);
                }else {
                    async.waterfall([
                        function (call) {
                            let sql = 'SELECT member_id ' +
                                ' FROM member_user ' +
                                ' WHERE phone_number = ? ';
                            connection.query(sql, [phoneNumber], function (queryErr, rows) {
                                if (queryErr) {
                                    console.log('WXMemberController.js(81)'+queryErr);
                                    call('获取用户信息失败！');
                                } else if (rows.length == 0){
                                    console.log('WXMemberController.js(84)'+'手机号不存在');
                                    call(null, true);
                                } else {
                                    console.log('WXMemberController.js(87)'+'手机号已存在');
                                    call(null, false);
                                }
                            });
                        },
                        function (arg1,call) {
                            if(arg1 == true){
                                let sql = 'SELECT member_id ' +
                                    ' FROM member_user ' +
                                    ' WHERE openid = ? ';
                                console.log('WXMemberController.js(97)'+userInfo.openid);
                                console.log('WXMemberController.js(98)'+sql);
                                connection.query(sql, [userInfo.openid], function (queryErr, rows) {
                                    if (queryErr) {
                                        console.log('WXMemberController.js(100)'+queryErr);
                                        call('获取用户信息失败！');
                                    } else if (rows.length == 0){
                                        //未注册
                                        call(null, false);
                                    } else {
                                        //已注册
                                        call(null, true);
                                    }
                                });
                            } else {
                                call('输入的手机号已存在！');
                            }
                        },
                        function (arg1, call) {
                            if (arg1 == false){
                                let sql = 'INSERT INTO member_user ' +
                                    ' (member_type, phone_number, openid ,nickname , sex ,province ,city ,country ,headimgurl ,createtime ,updatetime) ' +
                                    ' VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
                                connection.query(sql,
                                    [0, phoneNumber,
                                        userInfo.openid,
                                        userInfo.nickname, userInfo.sex, userInfo.province, userInfo.city, userInfo.country,
                                        userInfo.headimgurl, timestamp, timestamp],
                                    function (queryErr, result) {
                                        if (queryErr) {
                                            call('保存用户信息失败！');
                                        } else {
                                            call(null,result);
                                        }
                                    });
                            } else {
                                let sql = 'UPDATE member_user SET phone_number = ? , updatetime = ? ' +
                                    ' WHERE openid = ? ';
                                connection.query(sql,[phoneNumber, timestamp, userInfo.openid], function (queryErr, result) {
                                        if (queryErr) {
                                            call('更新用户信息失败！');
                                        } else {
                                            call(null,result);
                                        }
                                    });
                            }
                        }

                    ],function (err, result) {
                        if (err) {
                            callback(err,106);
                        } else {
                            callback(null,null,result);
                        }
                        connection.release();
                    })
                }
            });
        } else {
            callback('用户信息丢失，请从公众号菜单重新进入！',106)
        }
    },
    checkPhoneNumber:function (req, res, callback) {
        if ( req.signedCookies.userinfo && req.signedCookies.userinfo.openid ){
            let openid = req.signedCookies.userinfo.openid;
            console.log('WXMemberController.js(163)'+openid);
            DBPool.getPoolConnection('mtsc',function (err, connection) {
                let sql = 'SELECT *  FROM member_user WHERE openid = ? AND phone_number IS NOT NULL ';
                connection.query(sql, [openid], function (queryErr, rows) {
                    if (queryErr) {
                        console.log('WX-Member-log: line(97)'+ '查询用户信息失败');
                        callback('获取用户信息失败！',107);
                    } else if (rows.length == 0){
                        console.log('WX-Member-log: line(100)'+ '未绑定手机');
                        callback('未绑定手机！',10001);
                    } else {
                        console.log('WX-Member-log: line(103)'+'已生成记录');
                        callback(null,null,rows[0]);
                    }
                    connection.release();
                });
            });
        } else {
            callback('用户信息丢失，请从公众号菜单重新进入！',107)
        }
    },
    checkPhoneNumberById:function (openid, callback) {
        DBPool.getPoolConnection('mtsc',function (err, connection) {
            let sql = 'SELECT *  FROM member_user WHERE openid = ? AND phone_number IS NOT NULL ';
            connection.query(sql, [openid], function (queryErr, rows) {
                if (queryErr) {
                    console.log('WX-Member-log: line(97)'+ '查询用户信息失败');
                    callback('获取用户信息失败！',107);
                } else if (rows.length == 0){
                    console.log('WX-Member-log: line(100)'+ '未绑定手机');
                    callback('未绑定手机！',10001);
                } else {
                    console.log('WX-Member-log: line(103)'+'已生成记录');
                    callback(null,null,rows[0]);
                }
                connection.release();
            });
        });
    },
    queryConfig: function (req,callback) {
        // console.log('protocol: '+req.protocol);
        // console.log('host: '+req.host);
        // console.log('hostname: '+req.hostname);
        // console.log('originalUrl: '+req.originalUrl);

        let url = req.protocol + '://' + req.hostname + req.originalUrl; //获取当前url
        let data = sign(Jsapi.getJsapiTicket(), url);

        callback(data);
    }
};
